import React, {useEffect, useState} from 'react';
import {Editor, ShortcutKey} from 'amis-editor';
import {useModel} from "@@/plugin-model";

import '@fortawesome/fontawesome-free/css/all.css';
import '@fortawesome/fontawesome-free/css/v4-shims.css';
import '@fortawesome/fontawesome-free/css/fontawesome.css'
import 'amis/lib/themes/cxd.css';
import 'amis/lib/helper.css';
import 'amis/sdk/iconfont.css';
import 'amis-editor-core/lib/style.css';
import './scss/style.scss';
import {SchemaObject, setDefaultTheme} from 'amis';
import {toast} from 'amis';
import {useParams} from "@@/exports";
import {useRequest} from "@@/plugin-request";
import {requestContent, saveContent} from "@/services/wms-dev-tool/business-page-list";
import {Modal,Button} from "antd";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import {AlertComponent, ToastComponent } from 'amis';
import {debounce} from "lodash";
import {history} from "@umijs/max";

setDefaultTheme('cxd');
let host = `${window.location.protocol}//${window.location.host}`;

const schemaUrl = `${host}/schema.json`;

const PageDesigner: React.FC = () => {
  const [preview, setPreview] = useState(false)
  const {fetcher, notify, alert, copy} = useModel("amisEnv")
  const {id : pageId} = useParams()
  const [originContent,setOriginContent] = useState({
    type: 'page',
    body: '这是新增的页面。'
  } as SchemaObject)
  const [content,setContent] = useState(originContent)
  const permCode = JSON.parse(localStorage.getItem("permCode")||"")
  const dictArr = JSON.parse(localStorage.getItem("userInfo")||"").sysAllDictItems
  for (let key in dictArr) {
    if (dictArr.hasOwnProperty(key)) {
      console.log("dict-------------------",dictArr[key])
      for(let i=0;i<dictArr[key].length;i++){
        dictArr[key][i].label = dictArr[key][i].text;
        delete dictArr[key][i].text;
      }
    }
  }
  console.log("dict addr------------------>",dictArr)
  const userInfo = JSON.parse(localStorage.getItem("userInfo")||"").userInfo

  const{run:reqContent} = useRequest(requestContent,{
    manual:true,
    onSuccess:(res:any)=>{
      console.log('reqContent--------------',res)
      if(res.data.content){
        setOriginContent(JSON.parse(res.data.content))
      }
      setContent(JSON.parse(res.data.content))
    }
  })
  useEffect(()=>{
    reqContent(pageId)
  },[])

  const {run:save,error:saveErr} = useRequest(saveContent,{
    manual:true,
    onSuccess:()=>{
    }
  })

  const debounceSave = debounce(async ()=>{
    await save({
      id: pageId as string,
      content: JSON.stringify(content)
    })
    setOriginContent(content)
    if(!saveErr){
      toast.success("保存成功","提示")
    }
  },300)

  function onSaveClick() {
    debounceSave()
  }


  function onChange(value: any) {
    setContent(value)
  }

  const [modalOpen, setModalOpen] = useState(false);

  const handleOk = async () => {
    await save({
      id:pageId as string,
      content:JSON.stringify(content)
    })
    if(!saveErr){
      toast.success("保存成功",{
        title:'提示'
      })
      window.close()
      // history.replace('/business-page-list')
    }
  }

  const handleCancel = () => {
    setModalOpen(false);
  }

  const handleNotSaveExit = () => {
    setModalOpen(false);
    // history.replace('/business-page-list')
    window.close()
  }

  const showModal = () => {
    setModalOpen(true);
  };

  function exit() {
    console.log("exit---------------",JSON.stringify(originContent),JSON.stringify(content))
    if(JSON.stringify(originContent) !== JSON.stringify(content)){
      showModal()
      return
    }
    // history.replace('/business-page-list')
    window.close()
  }

  return (
    <div className="Editor-Demo">
      <ToastComponent key="toast"/>
      <AlertComponent key="alert" />
      <div className="Editor-header">
        <div className="Editor-title">界面编辑器</div>

        <div className="Editor-header-actions">
          <ShortcutKey/>
          <div
            className={`header-action-btn m-1 ${
              preview ? 'primary' : ''
            }`}
            onClick={() => {
              setPreview(!preview);
            }}
          >
            {preview ? '编辑' : '预览'}
          </div>
          {!preview && (
            <div className={`header-action-btn m-1`} onClick={onSaveClick}>
              保存
            </div>
          )}
          {!preview && (
            <div className={`header-action-btn exit-btn`} onClick={exit}>
              退出
            </div>
          )}
        </div>
      </div>
      <div className="Editor-inner">
        <Editor
          theme={'cxd'}
          preview={preview}
          value={content}
          onChange={onChange}
          onPreview={() => {
            setPreview(true);
          }}
          onSave={onSaveClick}
          className="is-fixed"
          data={{
            perm:permCode.auth,
            dict:dictArr,
            user:userInfo
          }}
          // showCustomRenderersPanel={true}
          amisEnv={{
            fetcher: fetcher,
            notify: notify,
            alert: alert,
            copy: copy
          }}
        />
      </div>
      <Modal
        open={modalOpen}
        title="提示"
        closable={false}
        footer={[
          <Button key="cancel" onClick={handleCancel}>取消</Button>,
          <Button key="submit" type="primary" onClick={handleOk}>是</Button>,
          <Button key="not" onClick={handleNotSaveExit}>否</Button>,
        ]}
      >
        <p>是否退出并保存内容？</p>
      </Modal>
    </div>
  );
}
export default PageDesigner
